package com.example.pceb.service.Impl;

import com.example.pceb.entity.BorrowRecord;
import com.example.pceb.entity.Resources;
import com.example.pceb.mapper.BorrowRecordMapper;
import com.example.pceb.mapper.ResourceMapper;
import com.example.pceb.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowRecordMapper borrowMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public void borrow(Long resourceId, String username) {
        Resources resource = resourceMapper.selectById(resourceId);
        if (Boolean.TRUE.equals(resource.getIsBorrowed())) {
            throw new RuntimeException("资源已被借出");
        }

        resource.setIsBorrowed(true);
        resourceMapper.updateById(resource);

        BorrowRecord record = new BorrowRecord();
        record.setResourceId(resourceId);
        record.setBorrowerUsername(username);
        record.setStatus("借出中");
        borrowMapper.insert(record);
    }

    @Override
    public void returnResource(Long recordId) {
        BorrowRecord record = borrowMapper.selectById(recordId);
        record.setStatus("已归还");
        record.setReturnTime(new Timestamp(System.currentTimeMillis()));
        borrowMapper.updateById(record);

        Resources resource = resourceMapper.selectById(record.getResourceId());
        resource.setIsBorrowed(false);
        resourceMapper.updateById(resource);
    }

    @Override
    public List<BorrowRecord> listRecords() {
        return borrowMapper.selectList(null);
    }
}